using System;
using System.IO;
using System.Net;

namespace AutoUpdater
{
    /// <summary>
    /// 下载进度事件参数
    /// </summary>
    public class DownloadProgressEventArgs : EventArgs
    {
        public int ProgressPercentage { get; set; }
        public long BytesReceived { get; set; }
        public long TotalBytesToReceive { get; set; }
    }

    /// <summary>
    /// 下载完成事件参数
    /// </summary>
    public class DownloadCompletedEventArgs : EventArgs
    {
        public bool Success { get; set; }
        public string LocalFilePath { get; set; }
        public Exception Error { get; set; }
    }

    /// <summary>
    /// 带超时设置的WebClient
    /// </summary>
    public class TimeoutWebClient : WebClient
    {
        public int Timeout { get; set; }

        public TimeoutWebClient(int timeout)
        {
            Timeout = timeout;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request != null)
                request.Timeout = Timeout;
            return request;
        }
    }

    /// <summary>
    /// 下载管理器（支持断点续传）
    /// </summary>
    public class DownloadManager
    {
        public event EventHandler<DownloadProgressEventArgs> ProgressChanged;
        public event EventHandler<DownloadCompletedEventArgs> DownloadCompleted;

        private TimeoutWebClient _webClient;
        private string _localFilePath;
        private long _startPoint = 0;

        public void StartDownload(string url, string localFilePath)
        {
            try
            {
                _localFilePath = localFilePath;

                // 检查是否支持断点续传
                if (File.Exists(localFilePath))
                {
                    _startPoint = new FileInfo(localFilePath).Length;
                    if (IsRangeSupported(url, _startPoint))
                    {
                        Logger.Info($"支持断点续传，从 {_startPoint} 字节开始下载");
                    }
                    else
                    {
                        Logger.Info("不支持断点续传，重新下载");
                        File.Delete(localFilePath);
                        _startPoint = 0;
                    }
                }

                _webClient = new TimeoutWebClient(30000);
                _webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
                _webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;

                // 设置请求头（断点续传）
                if (_startPoint > 0)
                {
                    _webClient.Headers.Add("Range", $"bytes={_startPoint}-");
                }

                // 开始下载
                _webClient.DownloadFileAsync(new Uri(url), localFilePath);
            }
            catch (Exception ex)
            {
                DownloadCompleted?.Invoke(this, new DownloadCompletedEventArgs
                {
                    Success = false,
                    LocalFilePath = localFilePath,
                    Error = ex
                });
            }
        }

        /// <summary>
        /// 检查服务器是否支持断点续传
        /// </summary>
        private bool IsRangeSupported(string url, long startPoint)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "HEAD";
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    return response.StatusCode == HttpStatusCode.OK &&
                           response.Headers["Accept-Ranges"] == "bytes" &&
                           response.ContentLength > startPoint;
                }
            }
            catch
            {
                return false;
            }
        }

        private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            // 计算实际进度（考虑断点续传的起始点）
            long actualBytesReceived = e.BytesReceived + _startPoint;
            long actualTotalBytes = e.TotalBytesToReceive > 0 ? e.TotalBytesToReceive + _startPoint : -1;

            int progressPercentage = 0;
            if (actualTotalBytes > 0 && actualBytesReceived > 0)
            {
                progressPercentage = (int)((double)actualBytesReceived / actualTotalBytes * 100);
            }

            ProgressChanged?.Invoke(this, new DownloadProgressEventArgs
            {
                ProgressPercentage = progressPercentage,
                BytesReceived = actualBytesReceived,
                TotalBytesToReceive = actualTotalBytes
            });
        }

        private void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null)
            {
                DownloadCompleted?.Invoke(this, new DownloadCompletedEventArgs
                {
                    Success = false,
                    LocalFilePath = _localFilePath,
                    Error = e.Error
                });
            }
            else
            {
                DownloadCompleted?.Invoke(this, new DownloadCompletedEventArgs
                {
                    Success = true,
                    LocalFilePath = _localFilePath
                });
            }

            // 清理资源
            _webClient.Dispose();
            _webClient = null;
        }

        /// <summary>
        /// 取消下载
        /// </summary>
        public void CancelDownload()
        {
            if (_webClient != null && _webClient.IsBusy)
            {
                _webClient.CancelAsync();
            }
        }
    }
}
